<script setup>
import { ref, onMounted, nextTick } from "vue"; // 1. 导入 nextTick
import { orderDetail, paymentOrder } from "@/apis/orderApi.js";
import { useRoute } from "vue-router";

const router = useRoute();
const payInfo = ref({});
const formHtml = ref(''); // 存储支付宝表单HTML

// 获取订单详情
const getPayInfo = async () => {
  const res = await orderDetail(router.query.id);
  payInfo.value = res.data;
};

onMounted(getPayInfo);

// 触发支付（获取表单并提交）
const payment = async () => {
  try {
    // 2. params 无需用 ref 包装，直接用普通对象
    const params = {
      "orderNumber": payInfo.value.number,
      "payMethod": 2
    };

    const res = await paymentOrder(params);
    // 确认接口返回的是完整表单HTML（包含<form>标签）
    formHtml.value = res.data;

    // 3. 等待DOM渲染完成后，手动触发表单提交
    await nextTick();
    const payForm = document.forms.namedItem('punchout_form'); // 对应表单的name属性
    if (payForm) {
      payForm.submit(); // 提交表单，跳转到支付宝
    } else {
      alert('支付表单加载失败，请重试');
    }
  } catch (err) {
    console.error('支付请求失败：', err);
    alert('获取支付信息失败，请稍后重试');
  }
};
</script>

<template>
  <div class="container">
    <!-- 支付宝表单容器（渲染后会自动提交，无需视觉显示） -->
    <div class="pay-bank">
      <div
          v-if="formHtml"
          v-html="formHtml"
          style="display: none;"/>
    </div>

    <div class="pay-info">
      <p>订单提交成功，请尽快完成支付</p>
      <p>支付还剩<span>20分30秒</span>，超时订单将会被取消</p>
      <el-button @click="payment">立即支付</el-button>
      <div class="amount">
        <span>应付金额</span>
        <span>&yen;{{(payInfo.amount + payInfo.packAmount).toFixed(2)}}</span>
      </div>
    </div>

    <div class="pay-type">
      <p>请选择以下支付方式</p>
      <div class="type">
        <p>支付平台</p>
        <a class="btn weixin" href="javascript:;"></a>
        <a class="btn alipay" href="javascript:;" @click.prevent="payment"></a> <!-- 支付宝图标点击也触发支付 -->
      </div>
    </div>
  </div>
</template>

<style scoped>
.container{
  max-width: 600px;
  min-width: 200px;
  width: 100%;

  margin: 0 auto;
  padding: 16px;
  border-radius: 15px;
}
/* 可添加支付页面样式，例如按钮、倒计时等 */
.pay-info {
  margin: 20px;
  padding: 15px;
  border: 1px solid #eee;
}
.amount {
  margin-top: 15px;
  color: #f00;
  font-size: 18px;
}
.type {
  margin: 10px 0;
}
.btn {
  display: inline-block;
  width: 80px;
  height: 30px;
  margin-right: 10px;
  border: 1px solid #ddd;
}
.btn.alipay {
  background: url('https://t.alipayobjects.com/images/T1HHFgXXVeXXXXXXXX.png') center no-repeat;
  background-size: contain;
}
</style>
